<?php

namespace App\Http\Requests;

use App\Helpers\ResponseHelper;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Request;

class RunErrandRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    public function rules(): array
    {
        $user = Request::user();
        return [
            'nick_name' => 'required|string|max:255',
            'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/', 'unique:run_errands,mobile,' . $user->id . ',user_id'],
            'school_id' => 'required|integer',
            'faculty_id' => 'required|integer',
            'specialty' => 'required|string',
            'id_number' => 'required|alpha_num|unique:run_errands,id_number,' . $user->id . ',user_id',
            'id_card_front' => 'required|string',
            'id_card_reverse_side' => 'required|string',
        ];
    }

    public function messages(): array
    {
        return [
            'nick_name.required' => '请填写姓名.',
            'mobile.required' => '请填写手机号.',
            'mobile.regex' => '手机号格式不正确.',
            'mobile.unique' => '手机号已存在.',
            'school_id.required' => '请选择学校.',
            'faculty_id.required' => '请选择学院.',
            'specialty.required' => '请填写专业.',
            'id_number.required' => '请填写身份证号.',
            'id_number.alpha_num' => '身份证号格式不正确.',
            'id_card_front.required' => '请上传身份证正面照.',
            'id_card_reverse_side.required' => '请上传身份证反面照.',
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        $errors = $validator->errors();
        // 返回自定义的 JSON 格式
        throw new HttpResponseException(ResponseHelper::error(message: $errors));
    }
}
